package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.common.RoleEnum;
import com.sqx.modules.health.dto.UserPasswordDTO;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.mapper.DictMapper;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.*;
import com.sqx.modules.health.vo.UserVo;
import com.sqx.modules.sys.entity.SysUserEntity;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Api(value = "app端用户相关接口", tags = "app端用户相关接口", description = "")
@RestController
@RequestMapping("/health/app")
public class AppUserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private ISurveyrecordService surveyrecordService;
    @Autowired
    private IRecordsetService recordsetService;
    @Autowired
    private IBusdictService busdictService;
    @Autowired
    private IAppCustomsService customsService;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private INcgDeviceWatchService ncgDeviceWatchService;
    @Autowired
    private IHospitalService hospitalService;
    @Autowired
    private IAppOrderService orderService;
    @Autowired
    private IAppProductService productService;
    @Autowired
    private IAppVcodeService vcodeService;
    @Autowired
    private IAppUserplanService userPlanService;
    @Autowired
    private IUserExpandService expandService; // 用户拓展 service
    @Autowired
    private IDepartmentService departmentService; // 科室service
    @Autowired
    private NcgWatchService ncgWatchService;
    @Autowired
    private IAppMessagesService messageService;

    @Autowired
    private IUserKinsfolkService userKinsfolkService;

    @Autowired
    private INcgDeviceWatchService watchService;

    @Autowired
    private JwtUtils jwtUtils;

    @ApiOperation(value = "App患者端登录", notes = "App患者端登录,传formdata Model对象")
    @PostMapping("/appLoginByHealth")
    public Object appLoginByHealth(String phone, String msg, String platform, Integer sysPhone, String password) {
        /*String phone = user.getPhone();
        String password = user.getPassword();*/
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        SysUserEntity user = new SysUserEntity();
        user.setPhone(phone);
        user.setPassword(password);
        return userService.appLoginByHealth(user);
    }

    @ApiOperation(value = "App患者端登录", notes = "App患者端登录,传formdata Model对象")
    @PostMapping("/patientLogin")
    public Object patientLogin(@RequestBody SysUserEntity user) {
        String phone = user.getPhone();
        String password = user.getPassword();
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return userService.appPatientLogin(user);
    }

    @ApiOperation(value = "App患者端注册", notes = "App患者端注册,传formdata Model对象")
    @PostMapping("/patientRegister")
    public Result patientRegister(@RequestBody SysUserEntity user) {
        String phone = user.getPhone();
        String password = user.getPassword();
        String username = user.getUsername();
        String cardid = user.getCardid();
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password) || StrUtil.isBlank(username) || StrUtil.isBlank(cardid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.appPatientRegister(user));
    }

    @ApiOperation(value = "App患者端添加医生", notes = "App患者端添加医生,传formdata")
    @PostMapping("/patientAddDoctor")
    public Result patientAddDoctor(@RequestParam Map<String, String> params) {

        String phone = params.get("phone");
        String token = params.get("token");
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        ////String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        SysUserEntity doctorUser = userService.findByPhone(phone);
        if (doctorUser == null || !"ROLE_H_DOCTOR".equals(doctorUser.getRole())) {
            return Result.error(Constants.CODE_600, "该医生不存在");
        } else {

            SysUserEntity patientUser = userService.findByUid(uid);
            patientUser.setHid(doctorUser.getHid());
            patientUser.setBelongsDoctor(doctorUser.getUserId());

            Map<String, Object> res = new HashMap<>();
            res.put("patientUser", patientUser);
            res.put("doctorUser", doctorUser);

            if (userService.saveOrUpdate(patientUser)) {
                return Result.success("添加成功", res);
            } else {
                return Result.error(Constants.CODE_600, "添加失败");
            }
        }
    }

    @ApiOperation(value = "App患者端添加营养师", notes = "App患者端添加营养师,传formdata")
    @PostMapping("/patientAddDietitian")
    public Result patientAddDietitian(@RequestParam Map<String, String> params) {

        String phone = params.get("phone");
        String token = params.get("token");
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        SysUserEntity doctorUser = userService.findByPhone(phone);
        if (doctorUser == null || !"ROLE_H_DIETITIAN".equals(doctorUser.getRole())) {
            return Result.error(Constants.CODE_600, "该营养师不存在");
        } else {

            SysUserEntity patientUser = userService.findByUid(uid);
            patientUser.setHid(doctorUser.getHid());
            patientUser.setBelongsDietitian(doctorUser.getUserId());

            Map<String, Object> res = new HashMap<>();
            res.put("patientUser", patientUser);
            res.put("doctorUser", doctorUser);

            if (userService.saveOrUpdate(patientUser)) {
                return Result.success("添加成功", res);
            } else {
                return Result.error(Constants.CODE_600, "添加失败");
            }
        }
    }

    @ApiOperation(value = "App患者端添加营养师", notes = "App患者端添加营养师,传formdata")
    @PostMapping("/patientAddHealthManager")
    public Result patientAddHealthManager(@RequestParam Map<String, String> params) {

        String phone = params.get("phone");
        String token = params.get("token");
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        SysUserEntity doctorUser = userService.findByPhone(phone);
        if (doctorUser == null || !"ROLE_H_DIETITIAN".equals(doctorUser.getRole())) {
            return Result.error(Constants.CODE_600, "该健康管理师不存在");
        } else {

            SysUserEntity patientUser = userService.findByUid(uid);
            patientUser.setHid(doctorUser.getHid());
            patientUser.setBelongsNurse(doctorUser.getUserId());

            Map<String, Object> res = new HashMap<>();
            res.put("patientUser", patientUser);
            res.put("doctorUser", doctorUser);

            if (userService.saveOrUpdate(patientUser)) {
                return Result.success("添加成功", res);
            } else {
                return Result.error(Constants.CODE_600, "添加失败");
            }
        }
    }

    @ApiOperation(value = "App患者端我的医生", notes = "App患者端我的医生,传formdata")
    @PostMapping("/patientDoctorList")
    public Result patientDoctorList(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        SysUserEntity patientUser = userService.findByUid(uid);

        if (ObjectUtil.isNotNull(patientUser.getBelongsDoctor())) {
            QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<SysUserEntity>()
                    .eq("user_id", patientUser.getBelongsDoctor());
            return Result.success(userService.list(wrapper));
        } else {
            return Result.success(new ArrayList<>());
        }
    }

    @ApiOperation(value = "App患者端我的营养师", notes = "App患者端我的营养师,传formdata")
    @PostMapping("/patientDietitianList")
    public Result patientDietitianList(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        SysUserEntity patientUser = userService.findByUid(uid);

        if (ObjectUtil.isNotNull(patientUser.getBelongsDoctor())) {
            QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<SysUserEntity>()
                    .eq("user_id", patientUser.getBelongsDietitian());
            return Result.success(userService.list(wrapper));
        } else {
            return Result.success(new ArrayList<>());
        }
    }

    @ApiOperation(value = "App患者端我的健康管理师", notes = "App患者端我的营养师,传formdata")
    @PostMapping("/patientHealthManagerList")
    public Result patientHealthManagerList(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        SysUserEntity patientUser = userService.findByUid(uid);

        if (ObjectUtil.isNotNull(patientUser.getBelongsDoctor())) {
            QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<SysUserEntity>()
                    .eq("user_id", patientUser.getBelongsNurse());
            return Result.success(userService.list(wrapper));
        } else {
            return Result.success(new ArrayList<>());
        }
    }

    @ApiOperation(value = "App患者端我的订单", notes = "App患者端我的订单,传formdata")
    @PostMapping("/patientOrderList")
    public Result patientOrderList(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        QueryWrapper<AppOrder> wrapper = new QueryWrapper<AppOrder>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid);

        List<AppOrder> orderList = orderService.list(wrapper);
        orderList.forEach(one -> {
            if (ObjectUtil.isNotEmpty(one.getProductid())) {
                AppProduct product = productService.getRedisByUid(one.getProductid());
                one.setProductInfo(ObjectUtil.isEmpty(product.getInfo()) ? product.getInfo() : product.getInfo());
                one.setProductIcon(ObjectUtil.isEmpty(product.getIcon()) ? product.getIcon() : product.getIcon());
                one.setTypeName(ObjectUtil.isEmpty(one.getType()) ? product.getIcon() : product.getIcon());
            }
            if (Integer.valueOf(one.getType()) == 1) {
                one.setTypeName("购买");
            } else {//hire
                one.setTypeName("出租");
            }
            if (one.getStatus() == 0) {
                one.setStatusName("待支付");
            } else if (one.getStatus() == 1) {
                one.setStatusName("已支付");
            } else if (one.getStatus() == 2) {
                one.setStatusName("已领取");
            } else if (one.getStatus() == 3) {
                one.setStatusName("已归还");
            } else {
                one.setStatusName("已退款");
            }
        });

        return Result.success(orderList);

    }

    @ApiOperation(value = "App患者端我的设备", notes = "App患者端我的设备,传formdata")
    @PostMapping("/patientDeviceList")
    public Result patientDeviceList(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid);
        List<NcgDeviceWatch> deviceList = ncgDeviceWatchService.list(wrapper);

        deviceList.forEach(one -> {
            if (ObjectUtil.isNotEmpty(one.getProductid())) {
                AppProduct product = productService.getRedisByUid(one.getProductid() + "");
                one.setName(ObjectUtil.isEmpty(product.getName()) ? "" : product.getName());
                one.setProductIcon(ObjectUtil.isEmpty(product.getIcon()) ? "" : product.getIcon());
            }
        });

        return Result.success(deviceList);

    }

    @ApiOperation(value = "App患者端绑定设备", notes = "App患者端绑定设备,传formdata")
    @PostMapping("/patientBindDevice")
    public Result patientBindDevice(@RequestParam Map<String, String> params) {

        String imei = params.get("imei");
        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(imei), "imei", imei);
        NcgDeviceWatch oneDevice = ncgDeviceWatchService.getOne(wrapper);
        if (oneDevice == null) {
            return Result.error(Constants.CODE_600, "没有该设备");
        } else {
            SysUserEntity patientUser = userService.findByUid(uid);
            if (StrUtil.isBlank(String.valueOf(patientUser.getBelongsDoctor()))) {
                return Result.error(Constants.CODE_600, "请先添加专属医生");
            } else {
                oneDevice.setStatus(2);
                oneDevice.setUid(Long.valueOf(uid));
                oneDevice.setDoctorid(patientUser.getBelongsDoctor());
                oneDevice.setUpdatetime(LocalDateTime.now());
                oneDevice.setPositionid(2);

                if (ncgDeviceWatchService.saveOrUpdate(oneDevice)) {
//                    //hsx 租赁用户 绑定设备医生，补充订单信息 限制单一产品订单   20220919  start 添加
//                    //根据租赁人或者患者uid,查找最新一个订单
//                    QueryWrapper<AppOrder> Querywrapper = new QueryWrapper<AppOrder>()
//                            //.eq(ObjectUtil.isNotEmpty(orderno), "orderno", orderno);
//                    .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
//                     .eq()
//                    AppOrder order =  orderService.getOne(Querywrapper);
//                    order.setStatus(3);//已经归还
//                    orderService.getOne()

                    //hsx 租赁用户 归还设备 解绑 20220919  end
                    return Result.success("绑定成功");
                } else {
                    return Result.error(Constants.CODE_600, "绑定失败");
                }

//                Record record = recordService.getLastTest(Long.valueOf(uid));
//                if (ObjectUtil.isNotEmpty(record)) {
//                    if (ObjectUtil.equals(record.getFlag(), 0) && ObjectUtil.equals(record.getImei(),imei)) {
//                        return Result.error(Constants.CODE_500, "绑定失败,设备使用中,请联系管理员");
//                    }
//                }
//                ncgDeviceWatchService.editBinding(uid,patientUser.getBelongsDoctor(),imei);
//                Record aaRecord = new Record();
//                aaRecord.setUid(Long.valueOf(uid));
//                aaRecord.setDoctorid(patientUser.getBelongsDoctor());
//                aaRecord.setImei(imei);
//                aaRecord.setType(jsonObject.getInteger("type"));
//                aaRecord.setRecordtime(DateUtil.now());
//                aaRecord.setFlag(0);
//                // 保存测试记录
//                saveRecords(jsonObject);
//                recordService.saveOrUpdate(aaRecord);
            }
        }
    }

//    private void saveRecords(JSONObject jsonObject) {
//        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
//                .eq(ObjectUtil.isNotEmpty(jsonObject.getString("imei")), "imei", jsonObject.getString("imei"));
//
//        NcgDeviceWatch watch = ncgDeviceWatchService.getOne(wrapper);
//        Recordset recordset = new Recordset();
//        recordset.setImei(jsonObject.getString("imei"));
//        recordset.setUid(jsonObject.getLong("uid"));
//        recordset.setDocid(jsonObject.getLong("doctorid"));
////        recordset.setStatus(watch.getStatus());
//        recordset.setStatus(0);
////        recordset.setDevicename(watch.getDevicename());
//        recordset.setStartdate(LocalDateTime.now());
//        recordset.setDevicetype(Integer.valueOf(watch.getType()));
//        recordsetService.saveOrUpdate(recordset);
//
//    }

//    /**
//     * 患者绑定设备
//     * 参数 imei，uid
//     */
//    @ApiOperation(value = "患者绑定设备",notes ="患者绑定设备")
//    @GetMapping(value = "/binddevice")
//    public Result bindDevice(@RequestParam Map<String, String> params) {
//        String imei = params.get("imei");
//        String uid = params.get("uid");
//        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
//                .eq(ObjectUtil.isNotEmpty(imei), "imei", imei);
//        NcgDeviceWatch oneDevice =  ncgDeviceWatchService.getOne(wrapper);
//        if(oneDevice!=null){
//            Integer status = 3; // 修改状态为 用户绑定状态
//            Integer num = hospitalService.binding(StringUtil.toString(oneDevice.getId()), uid, status);
//            // 绑定用户的同时将数据保存到用户设备表
//            Integer saveNum = hospitalService.saveUserDevice(StringUtil.toString(oneDevice.getId()),uid);
//            if (num != 0 && saveNum != 0) {
//                return Result.success("绑定成功");
//            }
//            return Result.error(Constants.CODE_500, "绑定失败");
//        }
//        return Result.error(Constants.CODE_500, "绑定失败");
//    }
//

    /**
     * 修改密码
     *
     * @param userPasswordDTO
     * @return
     */
    @ApiOperation(value = "App患者端修改密码", notes = "App患者端修改密码")
    @PostMapping("/patientPassword")
    public Result patientPassword(@RequestBody UserPasswordDTO userPasswordDTO) {

        boolean update = userService.updatePassword(userPasswordDTO);
        if (update) {
            return Result.success("修改成功");
        } else {
            return Result.error(Constants.CODE_500, "修改失败");
        }
    }

    /**
     * 数字验证码
     *
     * @return CommonResult
     */
    @ApiOperation(value = "app患者端获取验证码", notes = "app患者端获取验证码")
    @PostMapping("/getLoginverifyCode")
    public Result getLoginverifyCode(@RequestParam Map<String, String> params) {

        String phone = params.get("phone");
        if (StrUtil.isBlank(phone)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        int randomNum = (int) ((Math.random() * 9 + 1) * 100000); // 随机数 6 位
        Date now = new Date();
        AppVcode vcode = new AppVcode();
        vcode.setPhone(phone);
        vcode.setVcode(StringUtil.toString(randomNum));
        vcode.setCreatetime(LocalDateTime.now());
        vcodeService.save(vcode);
        return Result.success(vcode);
    }

    /**
     * 修改用餐习惯
     */
    @ApiOperation(value = "修改用餐资料", notes = "修改用餐资料")
    @PostMapping("/livingedit")
    public Result livingedit(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        QueryWrapper<AppCustoms> wrapper = new QueryWrapper<AppCustoms>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid);

        return Result.success(customsService.getOne(wrapper));

    }

    /**
     * 患者端退出登录
     */
    @ApiOperation(value = "app患者端退出登录", notes = "app患者端退出登录")
    @PostMapping("/patientOutLogin")
    public Result patientOutLogin(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        SysUserEntity patientUser = userService.findByUid(uid);
        patientUser.setToken("");
        patientUser.setImid("");
        patientUser.setImtoken("");
        //patientUser.setImtokenexpired(null);

        if (userService.saveOrUpdate(patientUser)) {
            return Result.success("退出登录成功");
        } else {
            return Result.error(Constants.CODE_600, "退出登录失败");
        }
    }

    /**
     * 患者端健康指导数据信息
     */
    @ApiOperation(value = "app患者端健康指导数据", notes = "app患者端健康指导数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "type", value = "类型：1-饮食;2-运动;3-药物", paramType = "Integer"),
    })
    @PostMapping("/patientHealthData")
    public Result patientHealthData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String type = params.get("type");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(type)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<AppUserplan> wrapper = new QueryWrapper<AppUserplan>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
                .eq(ObjectUtil.isNotEmpty(type), "type", type)
                .orderByDesc("createtime");
        List<AppUserplan> deviceList = userPlanService.list(wrapper);

        return Result.success(deviceList);

    }

//    // 条件查询
//    @ApiOperation(value = "获取手表数据", notes = "获取手表数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
//    })
//    @PostMapping("/getPatWatchData")
//    public Result getPatWatchData(@RequestParam Map<String, String> params){
//
//        String token = params.get("token");
//
//        if (StrUtil.isBlank(token)) {
//            return Result.error(Constants.CODE_400, "参数错误");
//        }
//        String uid = JWT.decode(token).getAudience().get(0);
        //String uid = jwtUtils.getUserIdByToken(token);
//
//        QueryWrapper<NcgDeviceWatch> uidWrapper = new QueryWrapper<NcgDeviceWatch>()
//                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
//                .eq("type", 5);
//        NcgDeviceWatch deviceWatch = ncgDeviceWatchService.getOne(uidWrapper);
//
//        if (deviceWatch == null) {
//
//            return Result.error(Constants.CODE_500, "未绑定手表设备");
//
//        }else {
//
//            String imei = deviceWatch.getImei();
//
//            QueryWrapper<NcgWatch> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select("imei,ifnull(sum(stepCount),0) as stepCount,ifnull(sum(remainElectricity),0) as remainElectricity,ifnull(sum(systolicBloodPressure),0) as systolicBloodPressure,ifnull(sum(diastolicBloodPressure),0) as diastolicBloodPressure,ifnull(sum(heartRate),0) as heartRate,ifnull(sum(bloodOxygen),0) as bloodOxygen,ifnull(sum(bodyTemperature),0) as bodyTemperature,createtime");
//            queryWrapper.eq(ObjectUtil.isNotEmpty(imei), "imei", imei);
//            queryWrapper.groupBy("createtime");
//            List<NcgWatch> getData =(List<NcgWatch>)ncgWatchService.list(queryWrapper);
//            List<NcgWatch> getDatanew = new ArrayList<>();
//            for(int i = 0;i<getData.size();i++ ){
//                NcgWatch one = getData.get(i);
//                if(one.getStepCount() > 0
//                        || one.getBloodOxygen() > 0
//                        || one.getDiastolicBloodPressure()>0
//                        || one.getSystolicBloodPressure() > 0
//                        || one.getHeartRate()>0
//                        || one.getBodyTemperature().doubleValue()>0
//                ){
//                    getDatanew.add(one);
//                }
//            }
//            Collections.sort(getDatanew, Comparator.comparing(NcgWatch::getCreatetime).reversed());
//
//            return  Result.success(getDatanew);
//        }
//    }

//    // 新增或更新
//    @PostMapping("/save")
//    @ApiOperation(value = "新增或更新用户信息", notes = "新增或更新用户信息")
//    public Result save(@RequestBody User user) {
//        if (user.getId() == null || user.getId() == 0) {
//            // 判断数据库中是否已经存在当前openid
//            User openUser = userService.findByOpenid(user.getOpenid());
//            if (openUser != null) {
//                return Result.error(Constants.CODE_500, "该用户已存在,不能重复注册");
//            }
//            // 新增用户默认密码为123456
//            user.setPassword(user.getId() == null ? "123456" : user.getPassword());
//        }
//        // 调用方法  执行添加
//        Boolean save = userService.saveOrUpdate(user);
//        if (save) {
//            User service = userService.findByOpenid(user.getOpenid());
//            // 给用户一个默认的token app登录使用
//            service.setToken(service.getToken() == null ? TokenUtils.genToken(service.getId().toString(), service.getPassword()) : service.getToken());
//        }
//        return Result.success(save);
//    }


//    /**
//     * 换绑手机号校验
//     */
//    @ApiOperation(value = "换绑手机号校验")
//    @RequestMapping(value = "update/binding/verify", method = RequestMethod.POST)
//    public CommonResult<Boolean> updatePhoneVerify(@RequestBody @Validated UserBindingPhoneUpdateRequest request) {
//        return CommonResult.success(userService.updatePhoneVerify(request));
//    }
//
//    /**
//     * 绑定手机号
//     */
//    @ApiOperation(value = "换绑手机号")
//    @RequestMapping(value = "update/binding", method = RequestMethod.POST)
//    public CommonResult<Boolean> updatePhone(@RequestBody @Validated UserBindingPhoneUpdateRequest request) {
//        return CommonResult.success(userService.updatePhone(request));
//    }

//---------------------------------------------------以下为医生端----------------------------------------------------------


    @PostMapping("/doctorLogin")
    public Object doctorLogin(@RequestBody SysUserEntity user) {

        String phone = user.getPhone();
        String password = user.getPassword();
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        /*SysUserEntity userA = userService.appPatientLogin(user);
        userService.saveOrUpdate(userA);*/
        return userService.appPatientLogin(user);
    }

    // 新增或修改患者(App端)
    @PostMapping("/savePatient")

    public Result savePatient(@RequestBody UserVo user) {
        SysUserEntity saveUser = new SysUserEntity();
        SysUserEntity aaUser = userService.findByPhone(user.getPhone());
        //新增
        if (aaUser == null) {
            //     新增用户默认密码为123456
            //
//            try {
//                TaiyiUtil.getDESSercretKey(user.getPhone().toString());
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
            //TaiyiUtil.
            user.setPassword(user.getId() == null ? "123456" : user.getPassword());
            user.setRole(RoleEnum.ROLE_USER.name());
            user.setType(0);
            BeanUtil.copyProperties(user, saveUser);
            return Result.success(userService.saveOrUpdate(saveUser));
        } else { //修改
            return Result.error(Constants.CODE_500, "该手机号已存在,请重新输入");
        }
    }

    @ApiOperation(value = "根据医生获取患者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "type", value = "数据类型 1 血糖 2 血压 3 动态血压 4 动态心电", paramType = "Integer")
    })
    @PostMapping("/getPatientsByDoctor")
    public Result getPatientsByDoctor(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String type = params.get("type");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(type)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                .and(o ->
                        o.eq(ObjectUtil.isNotEmpty(uid), "belongs_doctor", uid)
                                .or().eq(ObjectUtil.isNotEmpty(uid), "belongs_dietitian", uid))
                .eq("type", 0).orderByDesc("keynote");
        List<SysUserEntity> userList = userService.list(queryWrapper);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateFormatStr = dateFormat.format(date);
        int gg_num = 0;
//        List<Integer> aa = new ArrayList();
//        userList.forEach(user -> { // DateUtil.today()
//            Record record = recordService.getRecord(user.getId(),dateFormatStr, Integer.valueOf(type));
//            user.setRecord(record);
////            if (record != null){
////            }
//        });

        for (int i = 0; i < userList.size(); i++) {
            SysUserEntity user = userList.get(i);
            Record record = recordService.getRecord(user.getUserId(), dateFormatStr, Integer.valueOf(type));
            user.setRecord(record);
            if (record != null) {
                gg_num++;
            }
        }

        Collections.sort(userList, Comparator.nullsLast(new Comparator<SysUserEntity>() {
            @Override
            public int compare(SysUserEntity o1, SysUserEntity o2) {
                if (o1.getRecord() == null) {
                    return 1;
                }
                if (o2.getRecord() == null) {
                    return -1;
                }
                return o2.getRecord().getRecordtime().compareTo(o1.getRecord().getRecordtime());
            }
        }));

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("all_num", userList.size() - gg_num);
        resultMap.put("gg_num", gg_num);
        resultMap.put("userData", userList);

        JSONObject resultJson = new JSONObject(resultMap);

        return Result.success(resultJson);
    }

    // 根据ID查询一条记录
    @GetMapping("/findOnePatient")
    @ApiOperation(value = "根据ID查询一条记录用户信息(查看详细信息)", notes = "根据ID查询一条记录用户信息(查看详细信息)")
    public Result findOnePatient(@RequestParam Integer id) {
        return Result.success(userService.getById(id));
    }

    /**
     * 封装返回结果
     *
     * @param queryWrapper
     * @return
     */
    private List<Record> EncapsulateResult(QueryWrapper<Record> queryWrapper) {
        List<Record> list = recordService.list(queryWrapper);
        list.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getDoctorid())) {
                SysUserEntity user = userService.getRedisByUid(item.getDoctorid());
                item.setDoctorname(ObjectUtil.isNotEmpty(user.getUsername()) ? user.getUsername() : user.getNickName());
            }
        });
        return list;
    }

    @GetMapping("/findAllPatient")
    @ApiOperation(value = "查询全部患者信息", notes = "查询全部患者信息")
    public Result findAllPatient(@RequestParam("hid") String hid) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 0);
        if (!"null".equals(hid)) {
            queryWrapper.eq("hid", hid);
        }
        List<SysUserEntity> list = userService.list(queryWrapper);
        list.forEach(user -> user.setUsername(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName()));
        return Result.success(list);
    }

    @ApiOperation(value = "获取检测结果", notes = "获取检测结果")
    @PostMapping("getPatientData")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "uid", value = "患者id", paramType = "Long"),
            @ApiImplicitParam(name = "type", value = "数据类型 1 血糖 2血压 3动态血压 4动态心电 5手表数据", paramType = "Integer"),
    })
    public Result getPatientData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String type = params.get("type");
        String uid = params.get("uid");
        if (StrUtil.isBlank(token) || StrUtil.isBlank(type) || StrUtil.isBlank(uid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        String doctorUid = JWT.decode(token).getAudience().get(0);

        if (Integer.valueOf(type) == 5) {
            QueryWrapper<NcgDeviceWatch> uidWrapper = new QueryWrapper<NcgDeviceWatch>()
                    .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
                    .eq("type", 5);
            NcgDeviceWatch deviceWatch = ncgDeviceWatchService.getOne(uidWrapper);
            if (deviceWatch == null) {
                return Result.error(Constants.CODE_500, "未绑定手表设备");
            } else {
                String imei = deviceWatch.getImei();
                QueryWrapper<NcgWatch> queryWrapper = new QueryWrapper<>();
                queryWrapper.select("imei,ifnull(sum(step_count),0) as stepCount,ifnull(sum(remain_electricity),0) as remainElectricity,ifnull(sum(systolic_blood_pressure),0) as systolicBloodPressure,ifnull(sum(diastolic_blood_pressure),0) as diastolicBloodPressure,ifnull(sum(heart_rate),0) as heartRate,ifnull(sum(blood_oxygen),0) as bloodOxygen,ifnull(sum(body_temperature),0) as bodyTemperature,createtime");
                queryWrapper.eq(ObjectUtil.isNotEmpty(imei), "imei", imei);
                queryWrapper.groupBy("createtime");
                List<NcgWatch> getData = (List<NcgWatch>) ncgWatchService.list(queryWrapper);
                List<NcgWatch> getDatanew = new ArrayList<>();
                for (int i = 0; i < getData.size(); i++) {
                    NcgWatch one = getData.get(i);
                    if (one.getStepCount() > 0
                            || one.getBloodOxygen() > 0
                            || one.getDiastolicBloodPressure() > 0
                            || one.getSystolicBloodPressure() > 0
                            || one.getHeartRate() > 0
                            || one.getBodyTemperature().doubleValue() > 0
                    ) {
                        getDatanew.add(one);
                    }
                }
                Collections.sort(getDatanew, Comparator.comparing(NcgWatch::getCreatetime).reversed());
                return Result.success(getDatanew);
            }
        } else {

            QueryWrapper<Record> queryWrapper = new QueryWrapper<Record>()
                    .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
                    .eq(ObjectUtil.isNotEmpty(type), "type", type)
                    .eq("flag", 1)
                    .orderByDesc("recordtime");
            return Result.success(EncapsulateResult(queryWrapper));
        }
    }

    /**
     * 医生端健康指导数据信息
     */
    @ApiOperation(value = "app医生端健康指导数据", notes = "app医生端健康指导数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "type", value = "类型：1-饮食;2-运动;3-药物", paramType = "Integer"),
            @ApiImplicitParam(name = "uid", value = "患者id", paramType = "String"),
    })
    @PostMapping("/doctorHealthData")
    public Result doctorHealthData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String type = params.get("type");
        String uid = params.get("uid");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(type) || StrUtil.isBlank(uid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        String doctorid = JWT.decode(token).getAudience().get(0);
        SysUserEntity user = userService.getById(uid);

        QueryWrapper<AppUserplan> queryWrapper = new QueryWrapper<AppUserplan>()
                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
                .eq(ObjectUtil.isNotEmpty(type), "type", type)
                .eq("isdelete", 0)
                .and(o ->
                        o.eq(ObjectUtil.isNotEmpty(doctorid), "doctorid", user.getBelongsDoctor())
                                .or().eq(ObjectUtil.isNotEmpty(doctorid), "doctorid", user.getBelongsDietitian())
                )
                .orderByDesc("createtime");

        List<AppUserplan> deviceList = userPlanService.list(queryWrapper);

        return Result.success(deviceList);

    }

    @ApiOperation(value = "获取患者列表", notes = "获取患者列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
    })
    @PostMapping("getPatientList")
    public Result getPatientList(@RequestParam Map<String, String> params) {

        String token = params.get("token");

        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                .and(o ->
                        o.eq(ObjectUtil.isNotEmpty(uid), "belongs_doctor", uid)
                                .or().eq(ObjectUtil.isNotEmpty(uid), "belongs_dietitian", uid)
                )
                .eq("type", 0);

//        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();

        List<SysUserEntity> userList = userService.list(queryWrapper);

        List<UserVo> userVosList = MyBeanUtil.collectionCopy(userList, UserVo.class);

        userVosList.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getNickName())) {
                item.setFfName(ChineseCharacterUtil.convertHanzi2Pinyin(item.getNickName(), false));
            }
        });

        return Result.success(userVosList);

    }

    /**
     * 医生端健康指导数据信息
     */
    @ApiOperation(value = "app医生端获取动态血压详细数据", notes = "app医生端获取动态血压详细数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "patid", value = "批次号", paramType = "String"),
    })
    @PostMapping("/getDyPressureData")
    public Result getDyPressureData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String patid = params.get("patid");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(patid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        String doctorid = JWT.decode(token).getAudience().get(0);

        QueryWrapper<Surveyrecord> queryWrapper = new QueryWrapper<Surveyrecord>()
                .eq(ObjectUtil.isNotEmpty(patid), "patid", patid)
                .orderByDesc("sampleDate");

        List<Surveyrecord> recordList = surveyrecordService.list(queryWrapper);

        return Result.success(recordList);

    }

//    // 条件查询
//    @ApiOperation(value = "获取手表数据", notes = "获取手表数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
//            @ApiImplicitParam(name = "uid", value = "uid", paramType = "患者id")
//    })
//    @PostMapping("/getDocWatchData")
//    public Result getDocWatchData(@RequestParam Map<String, String> params){
//
//        String token = params.get("token");
//        String uid = params.get("uid");
//
//        if (StrUtil.isBlank(token) || StrUtil.isBlank(uid)) {
//            return Result.error(Constants.CODE_400, "参数错误");
//        }
//        String doctorUid = JWT.decode(token).getAudience().get(0);
//
//        QueryWrapper<NcgDeviceWatch> uidWrapper = new QueryWrapper<NcgDeviceWatch>()
//                .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
//                .eq("type", 5);
//        NcgDeviceWatch deviceWatch = ncgDeviceWatchService.getOne(uidWrapper);
//
//        if (deviceWatch == null) {
//
//            return Result.error(Constants.CODE_500, "未绑定手表设备");
//
//        }else {
//
//            String imei = deviceWatch.getImei();
//
//            QueryWrapper<NcgWatch> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select("imei,ifnull(sum(stepCount),0) as stepCount,ifnull(sum(remainElectricity),0) as remainElectricity,ifnull(sum(systolicBloodPressure),0) as systolicBloodPressure,ifnull(sum(diastolicBloodPressure),0) as diastolicBloodPressure,ifnull(sum(heartRate),0) as heartRate,ifnull(sum(bloodOxygen),0) as bloodOxygen,ifnull(sum(bodyTemperature),0) as bodyTemperature,createtime");
//            queryWrapper.eq(ObjectUtil.isNotEmpty(imei), "imei", imei);
//            queryWrapper.groupBy("createtime");
//            List<NcgWatch> getData =(List<NcgWatch>)ncgWatchService.list(queryWrapper);
//            List<NcgWatch> getDatanew = new ArrayList<>();
//            for(int i = 0;i<getData.size();i++ ){
//                NcgWatch one = getData.get(i);
//                if(one.getStepCount() > 0
//                        || one.getBloodOxygen() > 0
//                        || one.getDiastolicBloodPressure()>0
//                        || one.getSystolicBloodPressure() > 0
//                        || one.getHeartRate()>0
//                        || one.getBodyTemperature().doubleValue()>0
//                ){
//                    getDatanew.add(one);
//                }
//            }
//            Collections.sort(getDatanew, Comparator.comparing(NcgWatch::getCreatetime).reversed());
//
//            return  Result.success(getDatanew);
//        }
//    }

//    ---------------------------------------------------共用----------------------------------------------------------

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
    })
    @PostMapping("getUserData")
    public Result getUserData(@RequestParam Map<String, String> params) {

        String token = params.get("token");

        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        SysUserEntity user = userService.getById(uid); // 首先获取用户表所有信息
        // 根据角色进行判断  是否需要从拓展表获取数据
        if (user.getType() == 0 || StringUtils.isBlank(user.getRole())) {
            // 普通用户角色  直接返回
            return Result.success(user);
        }
        // 医院相关角色  去拓展表获取数据 并进行拼接
        UserExpand expandByFlag = expandService.getExpandByFlag(user.getExpandflag());
        UserVo result = new UserVo();
        BeanUtil.copyProperties(user, result);
        if (ObjectUtil.isNotEmpty(user.getHid())) {
            Hospital hospital = hospitalService.getById(user.getHid());
            result.setHname(hospital.getName());
        }
        result.setDepartment(expandByFlag.getDepartment());
        Department department = departmentService.getById(expandByFlag.getDepartment());
        if (ObjectUtil.isNotEmpty(department)) {
            result.setDepartmentName(department.getName());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getContent())) {
            result.setContent(expandByFlag.getContent());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getExp())) {
            result.setExp(expandByFlag.getExp());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getPosition())) {
            result.setPosition(expandByFlag.getPosition());
        }
        if (ObjectUtil.isNotEmpty(expandByFlag.getPortrait())) {
            result.setPortrait(expandByFlag.getPortrait());
        }
        return Result.success(result);

    }


    @ApiOperation(value = "获取患者信息", notes = "获取患者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "uid", paramType = "患者uid"),
    })
    @PostMapping("getPatientDetail")
    public Result getPatientDetail(@RequestParam Map<String, String> params) {

        String uid = params.get("uid");

        if (StrUtil.isBlank(uid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        SysUserEntity user = userService.getById(uid); // 首先获取用户表所有信息

        return Result.success(user);

    }

    @ApiOperation(value = "获取患者信息", notes = "获取患者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imid", value = "imid", paramType = "患者imid"),
    })
    @PostMapping("getPatientDetailByImid")
    public Result getPatientDetailByImid(@RequestParam Map<String, String> params) {
        String imid = params.get("imid");
        if (StrUtil.isBlank(imid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        SysUserEntity user = userService.getOne(new QueryWrapper<SysUserEntity>().eq("imid", imid));
        return Result.success(user);
    }

    @ApiOperation(value = "获取聊天记录", notes = "获取聊天记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "uid", value = "聊天接收人的uid", paramType = "String"),
    })
    @PostMapping("getChatMessageData")
    public Result getChatMessageData(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String aa_uid = params.get("uid");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(aa_uid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        QueryWrapper<AppMessages> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("senduid", uid).eq("acceptuid", aa_uid);
        queryWrapper.or().eq("acceptuid", uid).eq("senduid", aa_uid);
        List<AppMessages> messageList = messageService.list(queryWrapper);

        return Result.success(messageList);
    }


//    @ApiOperation(value = "获取健康指导数据", notes = "获取健康指导数据")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
//            @ApiImplicitParam(name = "type", value = "类型：1-饮食;2-运动;3-药物", paramType = "Integer"),
//    })
//    @PostMapping("getUserHealthData")
//    public Result getUserHealthData(@RequestParam Map<String, String> params) {
//
//        String token = params.get("token");
//        String type = params.get("type");
//
//        if (StrUtil.isBlank(token) || StrUtil.isBlank(type)) {
//            return Result.error(Constants.CODE_400, "参数错误");
//        }
//
//        if(params.containsKey("uid")){
//            //医生端
//            String uid = params.get("uid");
//            String doctorid = JWT.decode(token).getAudience().get(0);
//
//            QueryWrapper<AppUserplan> queryWrapper = new QueryWrapper<AppUserplan>()
//                    .eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
//                    .eq(ObjectUtil.isNotEmpty(type), "type", type)
//                    .eq(ObjectUtil.isNotEmpty(doctorid), "doctorid", doctorid)
//                    .orderByDesc("createtime");
//
//            return Result.success(recordService.list(queryWrapper));
//
//        }else {
//            //患者端
//            String uid = JWT.decode(token).getAudience().get(0);
        //String uid = jwtUtils.getUserIdByToken(token);
//
//            QueryWrapper<Record> queryWrapper = new QueryWrapper<Record>().eq(ObjectUtil.isNotEmpty(uid), "uid", uid)
//                    .eq(ObjectUtil.isNotEmpty(type), "type", type)
//                    .orderByDesc("recordtime");
//
//            return Result.success(recordService.list(queryWrapper));
//
//
//        }
//    }

    // 分页查询
    @GetMapping("/findPrescriptPage")
    @ApiOperation(value = "分页查询业务字典表", notes = "分页查询业务字典表")
    public Result findPrescriptPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String searchName) {
        QueryWrapper<Busdict> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(ObjectUtil.isNotEmpty(searchName), "name", searchName);
        //queryWrapper.eq( "status", 1);
        queryWrapper.eq("isdelete", 0);
        queryWrapper.orderByAsc("type");
        return Result.success(busdictService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @PostMapping("/patientGetUserKinsfolkList")
    @ApiOperation(value = "App患者端获取亲属列表", notes = "App患者端获取亲属列表")
    public Result patientGetUserKinsfolkList(@RequestParam Map<String, String> params) {
        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<UserKinsfolk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid).orderByDesc("createtime");
        return Result.success(userKinsfolkService.list(queryWrapper));
    }

    @PostMapping("/patientGetUserListByKinsfolk")
    @ApiOperation(value = "App患者端获取亲属所属人员列表", notes = "App患者端获取亲属列表")
    public Result patientGetUserListByKinsfolk(@RequestParam Map<String, String> params) {
        String token = params.get("token");
        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        ////String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        QueryWrapper<UserKinsfolk> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("kinsfolkid", uid).orderByDesc("createtime");
        return Result.success(userKinsfolkService.list(queryWrapper));
    }

    @ApiOperation(value = "App患者端添加亲属信息", notes = "App患者端添加亲属信息,传formdata")
    @PostMapping("/patientAddUserKinsfolk")
    public Result patientAddUserKinsfolk(@RequestParam Map<String, String> params) {
        String nub = params.get("nub");
        String token = params.get("token");
        if (StrUtil.isBlank(nub) || StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);
        SysUserEntity kinsfolkUser = userService.getOne(new QueryWrapper<SysUserEntity>().eq("phone", nub).or().eq("cardid", nub));
        //User kinsfolkUser = userService.findByPhone(nub);
        if (kinsfolkUser == null) {
            return Result.error(Constants.CODE_600, "该账号不存在,请确认账号已注册");
        } else {
            QueryWrapper<UserKinsfolk> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid).eq("kinsfolkid", kinsfolkUser.getUserId());
            List<UserKinsfolk> userKinsfolkList = userKinsfolkService.list(queryWrapper);
            if (userKinsfolkList.size() > 0) {
                return Result.error(Constants.CODE_600, "这个账号已经添加过了哦");
            } else {
                SysUserEntity user = userService.findByUid(uid);
                UserKinsfolk userKinsfolk = new UserKinsfolk();
                userKinsfolk.setUid(Long.valueOf(uid));
                userKinsfolk.setUname(user.getNickName());
                userKinsfolk.setKinsfolkid(kinsfolkUser.getUserId());
                userKinsfolk.setPhone(kinsfolkUser.getPhone());
                userKinsfolk.setName(kinsfolkUser.getNickName());
                userKinsfolk.setCardid(kinsfolkUser.getCardid());

                if (userKinsfolkService.save(userKinsfolk)) {
                    return Result.success("添加成功");
                } else {
                    return Result.error(Constants.CODE_600, "添加失败");
                }
            }
        }
    }

    @ApiOperation(value = "App患者端删除亲属信息", notes = "App患者端删除亲属信息,传formdata")
    @PostMapping("/patientDelUserKinsfolk/{id}")
    public Result patientDelUserKinsfolk(@PathVariable("id") Long id) {
        if (userKinsfolkService.removeById(id)) {
            return Result.success("删除成功");
        } else {
            return Result.error(Constants.CODE_600, "删除失败");
        }
    }

    @PostMapping("/patientTransferDeviceCheck")
    @ApiOperation(value = "App患者端转借设备前检查", notes = "App患者端转借设备前检查")
    public Result patientTransferDeviceCheck(@RequestParam Map<String, String> params) {
        String token = params.get("token");
        String nub = params.get("nub");
        String imei = params.get("imei");

        if (StrUtil.isBlank(token)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        NcgDeviceWatch deviceWatch = watchService.getOne(new QueryWrapper<NcgDeviceWatch>().eq("imei", imei));
        if (!StringUtils.isEmpty(deviceWatch.getTransferuid())) {
            return Result.error(Constants.CODE_400, "设备借出尚未使用完毕,请等待");
        }

        List<SysUserEntity> transferUserList = userService.list(new QueryWrapper<SysUserEntity>().eq("phone", nub).or().eq("cardid", nub));
        if (transferUserList.size() > 0) {
            return Result.success(transferUserList.get(0));
        } else {
            return Result.error(Constants.CODE_400, "该账号不存在,请确认账号已注册");
        }
    }

    @ApiOperation(value = "App患者端转借设备", notes = "App患者端转借设备,传formdata")
    @PostMapping("/patientTransferDevice")
    public Result patientTransferDevice(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String transferuid = params.get("transferuid");
        String imei = params.get("imei");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(transferuid) || StrUtil.isBlank(imei)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        NcgDeviceWatch deviceWatch = watchService.getOne(new QueryWrapper<NcgDeviceWatch>().eq("imei", imei));
        deviceWatch.setTransferuid(transferuid);
        if (watchService.updateById(deviceWatch)) {
            return Result.success("转借成功");
        } else {
            return Result.error(Constants.CODE_600, "转借失败");
        }
    }

    @ApiOperation(value = "App医生端标记重点用户", notes = "App医生端标记重点用户,传formdata")
    @PostMapping("/doctorKeynote")
    public Result doctorKeynote(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String patientUid = params.get("patientUid");
        String status = params.get("status");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(patientUid) || StrUtil.isBlank(status)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        SysUserEntity user = userService.getById(patientUid);
        user.setKeynote(Integer.valueOf(status));
        if (userService.updateById(user)) {
            return Result.success("操作成功");
        } else {
            return Result.error(Constants.CODE_600, "操作失败");
        }
    }

    @ApiOperation(value = "根据护士获取患者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "type", value = "数据类型 1 所属患者 2 所有患者", paramType = "Integer")
    })
    @PostMapping("/getPatientsByNurse")
    public Result getPatientsByNurse(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String type = params.get("type");

        if (StrUtil.isBlank(token) || StrUtil.isBlank(type)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        //String uid = JWT.decode(token).getAudience().get(0);
        String uid = jwtUtils.getUserIdByToken(token);

        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                .eq("type", 0)
                .eq(ObjectUtil.isNotEmpty(uid) && "1".equals(type), "belongs_nurse", uid)
                .eq("isinner", 1)
                .eq("discharge", 0)
                .orderByDesc("keynote");
        List<SysUserEntity> userList = userService.list(queryWrapper);
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateFormatStr = dateFormat.format(date);
        int gg_num = 0;

        for (int i = 0; i < userList.size(); i++) {
            SysUserEntity user = userList.get(i);
            Record record = recordService.getRecord(user.getUserId(), dateFormatStr, Integer.valueOf(type));
            user.setRecord(record);
            if (record != null) {
                gg_num++;
            }
        }

        Collections.sort(userList, Comparator.nullsLast(new Comparator<SysUserEntity>() {
            @Override
            public int compare(SysUserEntity o1, SysUserEntity o2) {
                if (o1.getRecord() == null) {
                    return 1;
                }
                if (o2.getRecord() == null) {
                    return -1;
                }
                return o2.getRecord().getRecordtime().compareTo(o1.getRecord().getRecordtime());
            }
        }));

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("all_num", userList.size() - gg_num);
        resultMap.put("gg_num", gg_num);
        resultMap.put("userData", userList);
        JSONObject resultJson = new JSONObject(resultMap);
        return Result.success(resultJson);
    }

    @ApiOperation(value = "根据护士获取患者信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户token", paramType = "String"),
            @ApiImplicitParam(name = "type", value = "数据类型 1 所属患者 2 所有患者", paramType = "Integer")
    })
    @PostMapping("/getUserListByRole")
    public Result getUserListByRole(@RequestParam Map<String, String> params) {

        String hid = params.get("hid");
        String roleName = params.get("roleName");

        if (StrUtil.isBlank(hid) || StrUtil.isBlank(roleName)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<SysUserEntity>()
                .eq(StrUtil.isNotEmpty(hid), "hid", hid)
                .eq(StrUtil.isNotEmpty(roleName), "role", roleName)
                .orderByAsc("id");
        return Result.success(userService.list(queryWrapper));
    }

    @PostMapping("/saveInnerPatient")
    public Result saveInnerPatient(@RequestBody SysUserEntity user) {
        SysUserEntity saveUser = new SysUserEntity();
        SysUserEntity aaUser = userService.findByPhone(user.getPhone());
        //新增
        if (aaUser == null) {
            //     新增用户默认密码为123456
            //
//            try {
//                TaiyiUtil.getDESSercretKey(user.getPhone().toString());
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
            //TaiyiUtil.
            user.setPassword(user.getUserId() == null ? "123456" : user.getPassword());
            user.setRole(RoleEnum.ROLE_USER.name());
            user.setType(0);
            BeanUtil.copyProperties(user, saveUser);
            return Result.success(userService.saveOrUpdate(saveUser));
        } else { //修改
            return Result.error(Constants.CODE_500, "该手机号已存在,请重新输入");
        }
    }

    @ApiOperation(value = "App更新IM id", notes = "App更新IM id,传formdata")
    @PostMapping("/updateIMId")
    public Result updateIMId(@RequestParam Map<String, String> params) {

        String token = params.get("token");
        String uid = params.get("uid");
        String imId = params.get("imId");

        if (StrUtil.isBlank(uid) || StrUtil.isBlank(imId)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        ////String uid = JWT.decode(token).getAudience().get(0);
        SysUserEntity user = userService.getById(uid);
        user.setImid(imId);
        if (userService.updateById(user)) {
            return Result.success("操作成功");
        } else {
            return Result.error(Constants.CODE_600, "操作失败");
        }
    }

    @ApiOperation(value = "App更新IM id", notes = "App更新IM id,传formdata")
    @PostMapping("/getHospitalDataById")
    public Result getHospitalDataById(@RequestParam Map<String, String> params) {

        String hid = params.get("hid");

        if (StrUtil.isBlank(hid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(hospitalService.getById(hid));
    }


}
